package com.atguigu.eduorder.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.eduorder.entity.Order;
import com.atguigu.eduorder.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2023-04-28
 */
@RestController
@RequestMapping("/eduorder/order")
@CrossOrigin
public class OrderController {

    @Autowired
    private OrderService orderService;

    //只能买一次，如果存在该订单且未关闭，则不添加记录
    //根据课程id和用户id生成订单，返回订单编号，订单编号不是id


    /**
     * 生成订单
     * @param courseId
     * @param request
     * @return
     */
    @PostMapping("/saveOrders/{courseId}")
    public R saveOrders(@PathVariable String  courseId, HttpServletRequest request)
    {
        //获取token
        String memberIdByJwtToken = JwtUtils.getMemberIdByJwtToken(request);
        if(memberIdByJwtToken==null)
        {
            System.out.println("未登录");
            return R.error().message("未登录,请先登录");
        }
       String orderNo = orderService.createOrders(courseId,memberIdByJwtToken);
        return R.ok().data("orderNo",orderNo);
    }

    /**
     * 根据订单号获取订单信息
     * @param orderNo
     * @return
     */
    @GetMapping("/getOrderInfo/{orderNo}")
    public R getOrderInfo(@PathVariable String orderNo){

        Order order=orderService.getOrder(orderNo);
        return R.ok().data("order",order);
    }

    /**
     * 判断用户是否买了课程
     * 使用课程id和用户id查询order表状态
     * 0 未支付
     * 1支付
     * @param courseId
     * @param memberId
     * @return
     */
    @PostMapping("/isBuyCourse/{courseId}/{memberId}")
    public boolean isBuyCourse(@PathVariable("courseId") String courseId,@PathVariable("memberId") String memberId){

       boolean isBuy=orderService.isBuyCourse(courseId,memberId);
       return isBuy;

    }

}

